import React, { useState ,useRef} from 'react';
import XLSX from 'xlsx'

import { getCols } from '../../common/getCols'

import { connect } from 'umi'
import { Upload, Table, InputNumber, Form, Button, Drawer, Popover, Tabs ,message} from 'antd';

import { InboxOutlined } from '@ant-design/icons';
import Headbox from '@/components/pageHeaderBox'
import ConnetTags from '../../components/connetTags'

import styles from './addfiles.less';


const { Dragger } = Upload;
// 上传组件参数
const uprops = {
    accept: '.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    name: 'file',
    headers: {
        authorization: 'authorization-text',
    },
    maxCount: 1,
    listType: "picture"
};

// 读取xlxs文件转json
const setJsonData = (jsonArr, pos) => {
    // 返回表头信息
    var bt = jsonArr[pos]
    var cols = bt.map((it) => {
        return {
            title: it,
            dataIndex: it,
            key: it,
            render: (t) => {
                return (
                    <Popover content={<h1>{t}</h1>} trigger="hover">
                        <div>{t}</div>
                    </Popover>
                )
            }
        }
    })
    cols = cols.filter(i => i)
    // 获取数据
    // 设置数据起始偏移
    var newArr = jsonArr.slice(pos + 1);
    // 获取数据字段
    var k = bt.map(b => { return b })
    // 组合表格数据
    var datas = newArr.map((it, id) => {
        var kk = {}
        kk.key = id
        k.forEach((keys, ids) => {
            kk[keys] = it[ids]
        });
        return kk
    })
    console.log(datas)
    return { cols, datas }
}


const Auto = (props) => {
    const { route } = props
    const [drawer, setvis] = useState(false)
    const [jsonArr, setjsonArr] = useState([])
    const [jsons, setjson] = useState([])
    const [fjsons, setFjson] = useState([])
    const [columns, setColumns] = useState([])
    const [disp, setdisp] = useState('')
    const [tabid, setTabid] = useState(1);

    const childRef = useRef();

    return (
        <div>
            <Headbox title={route.title} extra={[]} />
            <div className={styles.basicBox}>
                <Dragger {...uprops}
                    style={{ display: disp }}
                    onRemove={e => {
                        setdisp('')
                        setColumns([])
                        setjson([])
                    }}
                    beforeUpload={file => {
                        setdisp('none')
                        var rABS = true;
                        const f = file;
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            var data = e.target.result;
                            if (!rABS) data = new Uint8Array(data);
                            var workbook = XLSX.read(data, {
                                type: rABS ? 'binary' : 'array'
                            });
                            // 假设我们的数据在第一个标签
                            var first_worksheet = workbook.Sheets[workbook.SheetNames[0]];
                            var jsonArrs = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 });
                            // 获取表头和数据
                            var { cols, datas } = setJsonData(jsonArrs, 0)
                            // 写入hook
                            setjsonArr([...jsonArrs])
                            setColumns([...cols])
                            setjson([...datas])

                            childRef.current.changeVal(99)

                        };
                        // 读取文件
                        if (rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
                        return false;
                    }}
                >
                    <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                    </p>
                    <p className="ant-upload-text">点击或拖入文件</p>
                    <p className="ant-upload-hint">
                        支持单个xlsx文件导入，如果表头数据不正确，请调整导入文件表头偏移量，多行表头请先在Excel软件中合并表头！
                    </p>
                </Dragger>
                <div style={{ display: disp !== '' ? '' : 'none', position: "relative" }}>
                    <Form layout="inline" style={{ padding: 10 }}>
                        <Form.Item label="导入文件表头偏移量">
                            <InputNumber min={0} max={jsonArr.length === 0 ? 0 : jsonArr.length - 1} defaultValue={0} onChange={(e) => {
                                if (jsonArr.length !== 0) {
                                    var { cols, datas } = setJsonData(jsonArr, e)
                                    setColumns([...cols])
                                    setjson([...datas])
                                }
                            }} />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" onClick={() => { 
                                setvis(true);
                                setTabid('1')
                                }}>关联表头</Button>
                        </Form.Item>
                        {/* <Form.Item>
                            <Button type="primary" onClick={() => { }}>导入数据到数据库</Button>
                        </Form.Item> */}
                    </Form>
                    <Table bordered size="small" scroll={{ x: 3500, y: 580 }} sticky dataSource={jsons} columns={columns} />
                </div>

            </div>
            <Drawer
                title="添加表头数据关联"
                placement="bottom"
                visible={drawer}
                getContainer={false}
                closable
                onClose={() => setvis(false)}
                height='85vh'
            >
                <div>
                    <Tabs activeKey={tabid} style={{ position: "relative" }} onTabClick={e => setTabid(e)}>
                        <Tabs.TabPane tab="（1）关联表头标签" key="1" style={{ overflowY: "scroll" }}>
                            <ConnetTags
                                onChange={(c) => {
                                    var list = []
                                    jsons.forEach((jt, jid) => {
                                        let str = {}
                                        str.key = jid
                                        for (const key in c) {
                                            str[key] = c[key].map(cc => jt[cc])
                                        }
                                        list.push(str)
                                    })
                                    setFjson([...list])
                                    setTabid('2')
                                }}
                                fcols={[...columns]}
                                data={jsons.length !== 0 ? jsons[0] : null}
                                ref={childRef}
                            />
                        </Tabs.TabPane>
                        <Tabs.TabPane tab="（2）检验转换数据" key="2" >
                            <Button className={styles.addbtn} type="primary" onClick={() => {
                                if(fjsons.length===0){
                                    message.warning('没有可添加的数据！！');
                                }else{

                                }
                            }}>添加数据到档案库</Button>
                            <Table bordered size="small" scroll={{ x: 3500, y: "60vh" }} sticky columns={getCols()} dataSource={fjsons} pagination={false} />
                        </Tabs.TabPane>
                    </Tabs>


                </div>
            </Drawer>
        </div>
    )
}

export default connect(({ global }) => ({
    global,
}))(Auto);

